package com.qingcloud.common.gateway.auth;

import com.qingcloud.base.pojo.Result;
import com.qingcloud.base.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.ServerAuthenticationEntryPoint;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *
 * 统一处理 AuthenticationException 异常
 * 401未授权异常处理，转换为JSON
 */
@Slf4j
public class JsonAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {
    @Override
    public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException e) {
        int status  = HttpStatus.UNAUTHORIZED.value();
        final Result<String> fail = Result.fail(status, e.getMessage(), "");
        return ResponseUtil.responseWrite(exchange, HttpStatus.UNAUTHORIZED.value(), fail);
    }

}
